const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const { sign } = require("jsonwebtoken");
const { secret } = require("./config");
const jwt = require("koa-jwt")({ secret }); //jwt加密解密中间件
const admin = require("./middleware/admin")();
const app = new Koa();
const router = new Router();
app.use(bodyParser()).use(router.routes()).use(router.allowedMethods());

router
  .post("/api/login", async (ctx, next) => {
    const user = ctx.request.body;
    //如果客户端有传过来,那我们签发令牌
    if (user && user.username) {
      let { username } = user;
      //token
      const token = sign({ username }, secret, { expiresIn: "1h" });
      ctx.body = {
        message: "得到了token",
        code: 1,
        token,
      };
    } else {
      ctx.body = {
        message: "参数错误",
        code: -1,
      };
    }
  })
  .get("/api/userInfo", jwt, async (ctx) => {
    ctx.body = {
      message: "token鉴权通过了",
      username: ctx.state.user.username,
    };
  })
  .get("/api/adminInfo", jwt, admin, async (ctx) => {
    ctx.body = {
      message: "welcome admin",
      username: ctx.state.user.username,
    };
  });
app.listen(3000, () => {
  console.log("http://localhost:3000");
});
